home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / scm / slib_inf.lha / slib.info-2 (.txt) < prev    next >
GNU Info File  |  1993-05-16  |  41KB  |  963 lines

  1. This is Info file slib.info, produced by Makeinfo-1.49 from the input
  2. file slib.texi.
  3.   This file documents SLIB, the portable Scheme library.
  4.   Copyright (C) 1993 Todd R. Eigenschink
  5.   Permission is granted to make and distribute verbatim copies of this
  6. manual provided the copyright notice and this permission notice are
  7. preserved on all copies.
  8.   Permission is granted to copy and distribute modified versions of this
  9. manual under the conditions for verbatim copying, provided that the
  10. entire resulting derived work is distributed under the terms of a
  11. permission notice identical to this one.
  12.   Permission is granted to copy and distribute translations of this
  13. manual into another language, under the above conditions for modified
  14. versions, except that this permission notice may be stated in a
  15. translation approved by the author.
  16. File: slib.info,  Node: Syntactic Closures,  Next: Syntax-Case Macros,  Prev: Macros That Work,  Up: Macro Implementations
  17. Syntactic Closures
  18. ==================
  19.   `(require 'syntactic-closures)'
  20.   Syntactic-closure macros.
  21.  -- Function: macro:expand EXPRESSION
  22.      Returns scheme code with the macros and derived expression types of
  23.      EXPRESSION expanded to primitive expression types.
  24.  -- Function: macro:eval EXPRESSION
  25.      `macro:eval' returns the value of EXPRESSION in the current top
  26.      level environment.  EXPRESSION can contain macro definitions. Side
  27.      effects of EXPRESSION will affect the top level environment.
  28.  -- Function: macro:load FILENAME
  29.      FILENAME should be a string.  If filename names an existing file,
  30.      the `macro:load' procedure reads Scheme source code expressions and
  31.      definitions from the file and evaluates them sequentially.  These
  32.      source code expressions and definitions may contain macro
  33.      definitions. The `macro:load' procedure does not affect the values
  34.      returned by `current-input-port' and `current-output-port'.
  35. Syntactic Closure Macro Facility
  36. --------------------------------
  37.                   A Syntactic Closures Macro Facility
  38.                             by Chris Hanson
  39.                             9 November 1991
  40.   This document describes "syntactic closures", a low-level macro
  41. facility for the Scheme programming language.  The facility is an
  42. alternative to the low-level macro facility described in the `Revised^4
  43. Report on Scheme.' This document is an addendum to that report.
  44.   The syntactic closures facility extends the BNF rule for TRANSFORMER
  45. SPEC to allow a new keyword that introduces a low-level macro
  46. transformer:
  47.      TRANSFORMER SPEC := (transformer EXPRESSION)
  48.   Additionally, the following procedures are added:
  49.      make-syntactic-closure
  50.      capture-syntactic-environment
  51.      identifier?
  52.      identifier=?
  53.   The description of the facility is divided into three parts.  The
  54. first part defines basic terminology.  The second part describes how
  55. macro transformers are defined.  The third part describes the use of
  56. "identifiers", which extend the syntactic closure mechanism to be
  57. compatible with `syntax-rules'.
  58. Terminology
  59. ...........
  60.   This section defines the concepts and data types used by the syntactic
  61. closures facility.
  62.    * "Forms" are the syntactic entities out of which programs are
  63.      recursively constructed.  A form is any expression, any
  64.      definition, any syntactic keyword, or any syntactic closure.  The
  65.      variable name that appears in a `set!' special form is also a
  66.      form.  Examples of forms:
  67.           17
  68.           #t
  69.           car
  70.           (+ x 4)
  71.           (lambda (x) x)
  72.           (define pi 3.14159)
  73.           if
  74.           define
  75.    * An "alias" is an alternate name for a given symbol.  It can appear
  76.      anywhere in a form that the symbol could be used, and when quoted
  77.      it is replaced by the symbol; however, it does not satisfy the
  78.      predicate `symbol?'.  Macro transformers rarely distinguish
  79.      symbols from aliases, referring to both as identifiers.
  80.    * A "syntactic" environment maps identifiers to their meanings. 
  81.      More precisely, it determines whether an identifier is a syntactic
  82.      keyword or a variable.  If it is a keyword, the meaning is an
  83.      interpretation for the form in which that keyword appears.  If it
  84.      is a variable, the meaning identifies which binding of that
  85.      variable is referenced.  In short, syntactic environments contain
  86.      all of the contextual information necessary for interpreting the
  87.      meaning of a particular form.
  88.    * A "syntactic closure" consists of a form, a syntactic environment,
  89.      and a list of identifiers.  All identifiers in the form take their
  90.      meaning from the syntactic environment, except those in the given
  91.      list.  The identifiers in the list are to have their meanings
  92.      determined later.  A syntactic closure may be used in any context
  93.      in which its form could have been used.  Since a syntactic closure
  94.      is also a form, it may not be used in contexts where a form would
  95.      be illegal. For example, a form may not appear as a clause in the
  96.      cond special form. A syntactic closure appearing in a quoted
  97.      structure is replaced by its form.
  98. Transformer Definition
  99. ......................
  100.   This section describes the `transformer' special form and the
  101. procedures `make-syntactic-closure' and `capture-syntactic-environment'.
  102.  -- Syntax: transformer EXPRESSION
  103.      Syntax: It is an error if this syntax occurs except as a
  104.      TRANSFORMER SPEC.
  105.      Semantics: The EXPRESSION is evaluated in the standard transformer
  106.      environment to yield a macro transformer as described below.  This
  107.      macro transformer is bound to a macro keyword by the special form
  108.      in which the `transformer' expression appears (for example,
  109.      `let-syntax').
  110.      A "macro transformer" is a procedure that takes two arguments, a
  111.      form and a syntactic environment, and returns a new form.  The
  112.      first argument, the "input form", is the form in which the macro
  113.      keyword occurred.  The second argument, the "usage environment",
  114.      is the syntactic environment in which the input form occurred. 
  115.      The result of the transformer, the "output form", is automatically
  116.      closed in the "transformer environment", which is the syntactic
  117.      environment in which the `transformer' expression occurred.
  118.      For example, here is a definition of a push macro using
  119.      `syntax-rules':
  120.           (define-syntax  push
  121.             (syntax-rules ()
  122.               ((push item list)
  123.                (set! list (cons item list)))))
  124.      Here is an equivalent definition using `transformer':
  125.           (define-syntax push
  126.             (transformer
  127.              (lambda (exp env)
  128.                (let ((item
  129.                   (make-syntactic-closure env '() (cadr exp)))
  130.                  (list
  131.                   (make-syntactic-closure env '() (caddr exp))))
  132.                  `(set! ,list (cons ,item ,list))))))
  133.      In this example, the identifiers `set!' and `cons' are closed in
  134.      the transformer environment, and thus will not be affected by the
  135.      meanings of those identifiers in the usage environment `env'.
  136.      Some macros may be non-hygienic by design.  For example, the
  137.      following defines a loop macro that implicitly binds `exit' to an
  138.      escape procedure.  The binding of `exit' is intended to capture
  139.      free references to `exit' in the body of the loop, so `exit' must
  140.      be left free when the body is closed:
  141.           (define-syntax loop
  142.             (transformer
  143.              (lambda (exp env)
  144.                (let ((body (cdr exp)))
  145.                  `(call-with-current-continuation
  146.                (lambda (exit)
  147.                  (let f ()
  148.                    ,@(map (lambda  (exp)
  149.                          (make-syntactic-closure env '(exit)
  150.                                      exp))
  151.                        body)
  152.                    (f))))))))
  153.      To assign meanings to the identifiers in a form, use
  154.      `make-syntactic-closure' to close the form in a syntactic
  155.      environment.
  156.  -- Function: make-syntactic-closure ENVIRONMENT FREE-NAMES FORM
  157.      ENVIRONMENT must be a syntactic environment, FREE-NAMES must be a
  158.      list of identifiers, and FORM must be a form.
  159.      `make-syntactic-closure' constructs and returns a syntactic closure
  160.      of FORM in ENVIRONMENT, which can be used anywhere that FORM could
  161.      have been used.  All the identifiers used in FORM, except those
  162.      explicitly excepted by FREE-NAMES, obtain their meanings from
  163.      ENVIRONMENT.
  164.      Here is an example where FREE-NAMES is something other than the
  165.      empty list.  It is instructive to compare the use of FREE-NAMES in
  166.      this example with its use in the `loop' example above: the examples
  167.      are similar except for the source of the identifier being left
  168.      free.
  169.           (define-syntax let1
  170.             (transformer
  171.              (lambda (exp env)
  172.                (let ((id (cadr exp))
  173.                  (init (caddr exp))
  174.                  (exp (cadddr exp)))
  175.                  `((lambda (,id)
  176.                  ,(make-syntactic-closure env (list id) exp))
  177.                ,(make-syntactic-closure env '() init))))))
  178.      `let1' is a simplified version of `let' that only binds a single
  179.      identifier, and whose body consists of a single expression.  When
  180.      the body expression is syntactically closed in its original
  181.      syntactic environment, the identifier that is to be bound by
  182.      `let1' must be left free, so that it can be properly captured by
  183.      the `lambda' in the output form.
  184.      To obtain a syntactic environment other than the usage
  185.      environment, use `capture-syntactic-environment'.
  186.  -- Function: capture-syntactic-environment PROCEDURE
  187.      `capture-syntactic-environment' returns a form that will, when
  188.      transformed, call PROCEDURE on the current syntactic environment.
  189.      PROCEDURE should compute and return a new form to be transformed,
  190.      in that same syntactic environment, in place of the form.
  191.      An example will make this clear.  Suppose we wanted to define a
  192.      simple `loop-until' keyword equivalent to
  193.           (define-syntax loop-until
  194.             (syntax-rules ()
  195.               ((loop-until id init test return step)
  196.                (letrec ((loop
  197.                      (lambda (id)
  198.                    (if test return (loop step)))))
  199.                  (loop init)))))
  200.      The following attempt at defining `loop-until' has a subtle bug:
  201.           (define-syntax loop-until
  202.             (transformer
  203.              (lambda (exp env)
  204.                (let ((id (cadr exp))
  205.                  (init (caddr exp))
  206.                  (test (cadddr exp))
  207.                  (return (cadddr (cdr exp)))
  208.                  (step (cadddr (cddr exp)))
  209.                  (close
  210.                   (lambda (exp free)
  211.                     (make-syntactic-closure env free exp))))
  212.                  `(letrec ((loop
  213.                     (lambda (,id)
  214.                       (if ,(close test (list id))
  215.                       ,(close return (list id))
  216.                       (loop ,(close step (list id)))))))
  217.                 (loop ,(close init '())))))))
  218.      This definition appears to take all of the proper precautions to
  219.      prevent unintended captures.  It carefully closes the
  220.      subexpressions in their original syntactic environment and it
  221.      leaves the `id' identifier free in the `test', `return', and
  222.      `step' expressions, so that it will be captured by the binding
  223.      introduced by the `lambda' expression.  Unfortunately it uses the
  224.      identifiers `if' and `loop' within that `lambda' expression, so if
  225.      the user of `loop-until' just happens to use, say, `if' for the
  226.      identifier, it will be inadvertently captured.
  227.      The syntactic environment that `if' and `loop' want to be exposed
  228.      to is the one just outside the `lambda' expression: before the
  229.      user's identifier is added to the syntactic environment, but after
  230.      the identifier loop has been added.
  231.      `capture-syntactic-environment' captures exactly that environment
  232.      as follows:
  233.           (define-syntax loop-until
  234.             (transformer
  235.              (lambda (exp env)
  236.                (let ((id (cadr exp))
  237.                  (init (caddr exp))
  238.                  (test (cadddr exp))
  239.                  (return (cadddr (cdr exp)))
  240.                  (step (cadddr (cddr exp)))
  241.                  (close
  242.                   (lambda (exp free)
  243.                     (make-syntactic-closure env free exp))))
  244.                  `(letrec ((loop
  245.                     ,(capture-syntactic-environment
  246.                       (lambda (env)
  247.                         `(lambda (,id)
  248.                        (,(make-syntactic-closure env '() `if)
  249.                         ,(close test (list id))
  250.                         ,(close return (list id))
  251.                         (,(make-syntactic-closure env '()
  252.                                       `loop)
  253.                          ,(close step (list id)))))))))
  254.                 (loop ,(close init '())))))))
  255.      In this case, having captured the desired syntactic environment,
  256.      it is convenient to construct syntactic closures of the
  257.      identifiers `if' and the `loop' and use them in the body of the
  258.      `lambda'.
  259.      A common use of `capture-syntactic-environment' is to get the
  260.      transformer environment of a macro transformer:
  261.           (transformer
  262.            (lambda (exp env)
  263.              (capture-syntactic-environment
  264.               (lambda (transformer-env)
  265.                 ...))))
  266. Identifiers
  267. ...........
  268.   This section describes the procedures that create and manipulate
  269. identifiers.  Previous syntactic closure proposals did not have an
  270. identifier data type -- they just used symbols.  The identifier data
  271. type extends the syntactic closures facility to be compatible with the
  272. high-level `syntax-rules' facility.
  273.   As discussed earlier, an identifier is either a symbol or an "alias".
  274.  An alias is implemented as a syntactic closure whose "form" is an
  275. identifier:
  276.      (make-syntactic-closure env '() 'a)
  277.         => an "alias"
  278.   Aliases are implemented as syntactic closures because they behave just
  279. like syntactic closures most of the time.  The difference is that an
  280. alias may be bound to a new value (for example by `lambda' or
  281. `let-syntax'); other syntactic closures may not be used this way. If an
  282. alias is bound, then within the scope of that binding it is looked up
  283. in the syntactic environment just like any other identifier.
  284.   Aliases are used in the implementation of the high-level facility
  285. `syntax-rules'.  A macro transformer created by `syntax-rules' uses a
  286. template to generate its output form, substituting subforms of the
  287. input form into the template.  In a syntactic closures implementation,
  288. all of the symbols in the template are replaced by aliases closed in
  289. the transformer environment, while the output form itself is closed in
  290. the usage environment.  This guarantees that the macro transformation
  291. is hygienic, without requiring the transformer to know the syntactic
  292. roles of the substituted input subforms.
  293.  -- Function: identifier? OBJECT
  294.      Returns `#t' if OBJECT is an identifier, otherwise returns `#f'. 
  295.      Examples:
  296.           (identifier? 'a)
  297.              => #t
  298.           (identifier? (make-syntactic-closure env '() 'a))
  299.              => #t
  300.           (identifier? "a")
  301.              => #f
  302.           (identifier? #\a)
  303.              => #f
  304.           (identifier? 97)
  305.              => #f
  306.           (identifier? #f)
  307.              => #f
  308.           (identifier? '(a))
  309.              => #f
  310.           (identifier? '#(a))
  311.              => #f
  312.      The predicate `eq?' is used to determine if two identifers are
  313.      "the same".  Thus `eq?' can be used to compare identifiers exactly
  314.      as it would be used to compare symbols.  Often, though, it is
  315.      useful to know whether two identifiers "mean the same thing".  For
  316.      example, the `cond' macro uses the symbol `else' to identify the
  317.      final clause in the conditional.  A macro transformer for `cond'
  318.      cannot just look for the symbol `else', because the `cond' form
  319.      might be the output of another macro transformer that replaced the
  320.      symbol `else' with an alias.  Instead the transformer must look
  321.      for an identifier that "means the same thing" in the usage
  322.      environment as the symbol `else' means in the transformer
  323.      environment.
  324.  -- Function: identifier=? ENVIRONMENT1 IDENTIFIER1 ENVIRONMENT2
  325.           IDENTIFIER2
  326.      ENVIRONMENT1 and ENVIRONMENT2 must be syntactic environments, and
  327.      IDENTIFIER1 and IDENTIFIER2 must be identifiers.  `identifier=?'
  328.      returns `#t' if the meaning of IDENTIFIER1 in ENVIRONMENT1 is the
  329.      same as that of IDENTIFIER2 in ENVIRONMENT2, otherwise it returns
  330.      `#f'. Examples:
  331.           (let-syntax
  332.               ((foo
  333.                 (transformer
  334.                  (lambda (form env)
  335.                (capture-syntactic-environment
  336.                 (lambda (transformer-env)
  337.                   (identifier=? transformer-env 'x env 'x)))))))
  338.             (list (foo)
  339.               (let ((x 3))
  340.                 (foo))))
  341.              => (#t #f)
  342.           (let-syntax ((bar foo))
  343.             (let-syntax
  344.                 ((foo
  345.               (transformer
  346.                (lambda (form env)
  347.                  (capture-syntactic-environment
  348.                   (lambda (transformer-env)
  349.                     (identifier=? transformer-env 'foo
  350.                           env (cadr form))))))))
  351.               (list (foo foo)
  352.                 (foobar))))
  353.              => (#f #t)
  354. Acknowledgements
  355. ................
  356.   The syntactic closures facility was invented by Alan Bawden and
  357. Jonathan Rees.  The use of aliases to implement `syntax-rules' was
  358. invented by Alan Bawden (who prefers to call them "synthetic names"). 
  359. Much of this proposal is derived from an earlier proposal by Alan
  360. Bawden.
  361. File: slib.info,  Node: Syntax-Case Macros,  Prev: Syntactic Closures,  Up: Macro Implementations
  362. Syntax-Case Macros
  363. ==================
  364.   `(require 'syntax-case)'
  365.   This is version 2.1 of `syntax-case', the low-level macro facility
  366. proposed and implemented by Robert Hieb and R. Kent Dybvig.
  367.   This version is further adapted by Harald Hanche-Olsen
  368. <hanche@imf.unit.no> to make it compatible with, and easily usable
  369. with, SLIB.  Mainly, these adaptations consisted of:
  370.    * Removing white space from `expand.pp' to save space in the
  371.      distribution.  This file is not meant for human readers anyway...
  372.    * Removed a couple of Chez scheme dependencies.
  373.    * Renamed global variables used to minimize the possibility of name
  374.      conflicts.
  375.    * Adding an SLIB-specific initialization file.
  376.    * Removing a couple extra files, most notably the documentation (but
  377.      see below).
  378.   If you wish, you can see exactly what changes were done by reading the
  379. shell script in the file `syncase.sh'.
  380.   The two PostScript files were omitted in order to not burden the SLIB
  381. distribution with them.  If you do intend to use `syntax-case',
  382. however, you should get these files and print them out on a PostScript
  383. printer.  They are available with the original `syntax-case'
  384. distribution by anonymous FTP in
  385. `cs.indiana.edu:/pub/scheme/syntax-case'.
  386.   To load syntax-case, execute:
  387.      (require 'syntax-case)
  388.      (require 'repl)
  389.      (repl:top-level macro:eval)
  390.   To check your sanity, run
  391.      (syncase:sanity-check)
  392.   Beware that `syntax-case' takes a long time to load -- about 20s on a
  393. SPARCstation SLC (with SCM) and about 90s on a Macintosh SE/30 (with
  394. Gambit).
  395. Notes
  396. -----
  397.   All R4RS syntactic forms are defined, including `delay'.  Along with
  398. `delay' are simple definitions for `make-promise' (into which `delay'
  399. expressions expand) and `force'.
  400.   `syntax-rules' and `with-syntax' (described in TR356) are defined.
  401.   `syntax-case' is actually defined as a macro that expands into calls
  402. to the procedure `syntax-dispatch' and the core form `syntax-lambda';
  403. do not redefine these names.
  404.   Several other top-level bindings not documented in TR356 are created:
  405.    * the "hooks" in `hooks.ss'
  406.    * the `build-' procedures in `output.ss'
  407.    * `expand-syntax' (the expander)
  408.   The syntax of define has been extended to allow `(define ID)', which
  409. assigns ID to some unspecified value.
  410.   We have attempted to maintain R4RS compatibility where possible.  The
  411. incompatibilities should be confined to `hooks.ss'.  Please let us know
  412. if there is some incompatibility that is not flagged as such.
  413.   Send bug reports, comments, suggestions, and questions to Kent Dybvig
  414. (dyb@iuvax.cs.indiana.edu).
  415. File: slib.info,  Node: Procedures,  Next: Standards Support,  Prev: Macro Implementations,  Up: Top
  416. Procedures
  417. **********
  418.   Anything that doesn't fall neatly into any of the other categories
  419. winds up here.
  420. * Menu:
  421. * Bit-Twiddling::               'logical
  422. * Common List Functions::       'common-list-functions
  423. * Format::                      'format
  424. * Generic-Write::               'generic-write
  425. * Line I/O::                    'line-i/o
  426. * Modular Arithmetic::          'modular
  427. * Multi-processing::            'process
  428. * Object-To-String::            'object->string
  429. * Plotting::                    'charplot
  430. * Pretty-Print::                'pretty-print, 'pprint-file
  431. * Prime Factorization::         'prime
  432. * Random Numbers::              'random
  433. * Sorting::                     'sort
  434. * Standard I/O::                'stdio
  435. * String-Case::                 'string-case
  436. * String Ports::                'string-port
  437. * Tektronix Graphics Support::
  438. File: slib.info,  Node: Bit-Twiddling,  Next: Common List Functions,  Prev: Procedures,  Up: Procedures
  439. Bit-Twiddling
  440. =============
  441.   `(require 'logical)'
  442.   The bit-twiddling functions are made available through the use of the
  443. `logical' package.  `logical' is loaded by inserting `(require
  444. 'logical)' before the code that uses these functions.
  445.  -- Function: logand N1 N1
  446.      Returns the integer which is the bit-wise AND of the two integer
  447.      arguments.
  448.      Example:
  449.           (number->string (logand #b011 #b100) 2)
  450.              => "0"
  451.           (number->string (logand #b10111 #b01101) 2)
  452.              => "101"
  453.  -- Function: logior N1 N2
  454.      Returns the integer which is the bit-wise OR of the two integer
  455.      arguments.
  456.      Example:
  457.           (number->string (logior #b10101010 #b01010101) 2)
  458.              => "11111111"
  459.           (number->string (logior #b10000000 #b00000001) 2)
  460.              => "10000001"
  461.  -- Function: logxor N1 N2
  462.      Returns the integer which is the bit-wise XOR of the two integer
  463.      arguments.
  464.      Example:
  465.           (number->string (logxor #b10101010 #b01010101) 2)
  466.              => "11111111"
  467.           (number->string (logxor #b111 #b010) 2)
  468.              => "101"
  469.  -- Function: lognot N
  470.      Returns the integer which is the 2s-complement of the integer
  471.      argument.
  472.      Example:
  473.           (number->string (lognot #b10000000) 2)
  474.              => "-10000001"
  475.           (number->string (lognot #b0) 2)
  476.              => "-1"
  477.  -- Function: ash INT COUNT
  478.      Returns an integer equivalent to `(inexact->exact (floor (* INT
  479.      (expt 2 COUNT))))'.
  480.      Example:
  481.           (number->string (ash #b1 3) 2)
  482.              => "1000"
  483.           (number->string (ash #b1010 -1) 2)
  484.              => "101"
  485.  -- Function: logcount N
  486.      Returns the number of bits in integer N.  If integer is positive,
  487.      the 1-bits in its binary representation are counted.  If negative,
  488.      the 0-bits in its two's-complement binary representation are
  489.      counted.  If 0, 0 is returned.
  490.      Example:
  491.           (logcount #b10101010)
  492.              => 4
  493.           (logcount 0)
  494.              => 0
  495.           (logcount -2)
  496.              => 1
  497.  -- Function: integer-length N
  498.      Returns the number of bits neccessary to represent N.
  499.      Example:
  500.           (integer-length #b10101010)
  501.              => 8
  502.           (integer-length 0)
  503.              => 0
  504.           (integer-length #b1111)
  505.              => 4
  506.  -- Function: integer-expt N K
  507.      Returns N raised to the non-negative integer exponent K.
  508.      Example:
  509.           (integer-expt 2 5)
  510.              => 32
  511.           (integer-expt -3 3)
  512.              => -27
  513.  -- Function: bit-extract N START END
  514.      Returns the integer composed of the START (inclusive) through END
  515.      (exclusive) bits of N.  The STARTth bit becomes the 0-th bit in
  516.      the result.
  517.      Example:
  518.           (number->string (bit-extract #b10101010 0 4) 2)
  519.              => "1010"
  520.           (number->string (bit-extract #b11111111 4 9) 2)
  521.              => "1111"
  522. File: slib.info,  Node: Common List Functions,  Next: Format,  Prev: Bit-Twiddling,  Up: Procedures
  523. Common List Functions
  524. =====================
  525.   `(require 'common-list-functions)'
  526.   The procedures below follow the Common LISP equivalents apart from
  527. optional arguments in some cases.
  528. * Menu:
  529. * List construction::
  530. * Lists as sets::
  531. * Lists as sequences::
  532. * Destructive list operations::
  533. * Non-list Common LISP functions::
  534. * Tree operations::
  535. File: slib.info,  Node: List construction,  Next: Lists as sets,  Prev: Common List Functions,  Up: Common List Functions
  536. List construction
  537. -----------------
  538.  -- Function: identity X
  539.      IDENTITY returns its argument.  (This probably shouldn't be in the
  540.      "list construction" section, since it doesn't construct anything,
  541.      but this is the section that makes the most sense.)
  542.      Example:
  543.           (identity 3)
  544.              => 3
  545.           (identity '(foo bar))
  546.              => (foo bar)
  547.           (map identity LST)
  548.              == (copy-list LST)
  549.  -- Function: make-list K . INIT
  550.      `make-list' creates and returns a list of K elements.  If INIT is
  551.      included, all elements in the list are initialized to INIT.
  552.      Example:
  553.           (make-list 3)
  554.              => (#<unspecified> #<unspecified> #<unspecified>)
  555.           (make-list 5 'foo)
  556.              => (foo foo foo foo foo)
  557.  -- Function: list* X . Y
  558.      Works like `list' except that the cdr of the last pair is the last
  559.      argument unless there is only one argument, when the result is
  560.      just that argument.  Sometimes called `cons*'.  E.g.:
  561.           (list* 1)
  562.              => 1
  563.           (list* 1 2 3)
  564.              => (1 2 . 3)
  565.           (list* 1 2 '(3 4))
  566.              => (1 2 3 4)
  567.           (list* ARGS '())
  568.              == (list ARGS)
  569.  -- Function: copy-list LST
  570.      `copy-list' makes a copy of LST using new pairs and returns it.
  571.      Only the top level of the list is copied, i.e., pairs forming
  572.      elements of the copied list remain `eq?' to the corresponding
  573.      elements of the original; the copy is, however, not `eq?' to the
  574.      original, but is `equal?' to it.
  575.      Example:
  576.           (copy-list '(foo foo foo))
  577.              => (foo foo foo)
  578.           (define q '(foo bar baz bang))
  579.           (define p q)
  580.           (eq? p q)
  581.              => #t
  582.           (define r (copy-list q))
  583.           (eq? q r)
  584.              => #f
  585.           (equal? q r)
  586.              => #t
  587.           (define bar '(bar))
  588.           (eq? bar (car (copy-list (list bar 'foo))))
  589.           => #t
  590. File: slib.info,  Node: Lists as sets,  Next: Lists as sequences,  Prev: List construction,  Up: Common List Functions
  591. Lists as sets
  592. -------------
  593.   `eq?' is used to test for membership by all the procedures below
  594. which treat lists as sets.
  595.  -- Function: adjoin E L
  596.      `adjoin' returns the adjoint of the element E and the list L. 
  597.      That is, if E is in L, `adjoin' returns L, otherwise, it returns
  598.      `(cons E L)'.
  599.      Example:
  600.           (adjoin 'baz '(bar baz bang))
  601.              => (bar baz bang)
  602.           (adjoin 'foo '(bar baz bang))
  603.              => (foo bar baz bang)
  604.  -- Function: union L1 L2
  605.      `union' returns the combination of L1 and L2 with duplicates
  606.      removed.
  607.      Example:
  608.           (union '(1 2 3 4) '(5 6 7 8))
  609.              => (4 3 2 1 5 6 7 8)
  610.           (union '(1 2 2 1) '(3 4 1 8))
  611.              => (2 3 4 1 8)
  612.  -- Function: intersection L1 L2
  613.      `intersection' returns all elements that are in both L1 and L2.
  614.      Example:
  615.           (intersection '(1 2 3 4) '(3 4 5 6))
  616.              => (3 4)
  617.           (intersection '(1 2 3 4) '(5 6 7 8))
  618.              => ()
  619.  -- Function: set-difference L1 L2
  620.      `set-difference' returns the union of all elements that are in L1
  621.      but not in L2.
  622.      Example:
  623.           (set-difference '(1 2 3 4) '(3 4 5 6))
  624.              => (1 2)
  625.           (set-difference '(1 2 3 4) '(1 2 3 4 5 6))
  626.              => ()
  627.  -- Function: member-if PRED LST
  628.      `member-if' returns LST if `(PRED ELEMENT)' is `#t' for any
  629.      ELEMENT in LST.  Returns `#f' if PRED does not apply to any
  630.      ELEMENT in LST.
  631.      Example:
  632.           (member-if vector? '(1 2 3 4))
  633.              => #f
  634.           (member-if number? '(1 2 3 4))
  635.              => (1 2 3 4)
  636.  -- Function: some PRED LST . MORE-LSTS
  637.      PRED is a boolean function of as many arguments as there are list
  638.      arguments to `some' i.e., LST plus any optional arguments. PRED is
  639.      applied to successive elements of the list arguments in order. 
  640.      `some' returns `#t' as soon as one of these applications returns
  641.      `#t', and is `#f' if none returns `#t'.  All the lists should have
  642.      the same length.
  643.      Example:
  644.           (some odd? '(1 2 3 4))
  645.              => #t
  646.           
  647.           (some odd? '(2 4 6 8))
  648.              => #f
  649.           
  650.           (some > '(2 3) '(1 4))
  651.              => #f
  652.  -- Function: every PRED LST . MORE-LSTS
  653.      `every' is analogous to `some' except it returns `#t' if every
  654.      application of PRED is `#t' and `#f' otherwise.
  655.      Example:
  656.           (every even? '(1 2 3 4))
  657.              => #f
  658.           
  659.           (every even? '(2 4 6 8))
  660.              => #t
  661.           
  662.           (every > '(2 3) '(1 4))
  663.              => #f
  664.  -- Function: notany PRED . LST
  665.      `notany' is analogous to `some' but returns `#t' if no application
  666.      of PRED returns `#t' or `#f' as soon as any one does.
  667.  -- Function: notevery PRED . LST
  668.      `notevery' is analogous to `some' but returns `#t' as soon as an
  669.      application of PRED returns `#f', and `#f' otherwise.
  670.      Example:
  671.           (notevery even? '(1 2 3 4))
  672.              => #t
  673.           
  674.           (notevery even? '(2 4 6 8))
  675.              => #f
  676.  -- Function: find-if PRED LST
  677.      `find-if' searches for the first ELEMENT in LST such that `(PRED
  678.      ELEMENT)' returns `#t'.  If it finds any such ELEMENT in LST,
  679.      ELEMENT is returned. Otherwise, `#f' is returned.
  680.      Example:
  681.           (find-if number? '(foo 1 bar 2))
  682.              => 1
  683.           
  684.           (find-if number? '(foo bar baz bang))
  685.              => #f
  686.           
  687.           (find-if symbol? '(1 2 foo bar))
  688.              => foo
  689.  -- Function: remove ELT LST
  690.      `remove' removes all occurrences of ELT from LST using `eqv?' to
  691.      test for equality and returns everything that's left. N.B.: other
  692.      implementations (Chez, Scheme->C and T, at least) use `equal?' as
  693.      the equality test.
  694.      Example:
  695.           (remove 1 '(1 2 1 3 1 4 1 5))
  696.              => (2 3 4 5)
  697.           
  698.           (remove 'foo '(bar baz bang))
  699.              => (bar baz bang)
  700.  -- Function: remove-if PRED LST
  701.      `remove-if' removes all ELEMENTs from LST where `(PRED ELEMENT)'
  702.      is `#t' and returns everything that's left.
  703.      Example:
  704.           (remove-if number? '(1 2 3 4))
  705.              => ()
  706.           
  707.           (remove-if even? '(1 2 3 4 5 6 7 8))
  708.              => (1 3 5 7)
  709.  -- Function: remove-if-not PRED LST
  710.      `remove-if-not' removes all ELEMENTs from LST for which `(PRED
  711.      ELEMENT)' is `#f' and returns everything that's left.
  712.      Example:
  713.           (remove-if-not number? '(foo bar baz))
  714.              => ()
  715.           (remove-if-not odd? '(1 2 3 4 5 6 7 8))
  716.              => (1 3 5 7)
  717. File: slib.info,  Node: Lists as sequences,  Next: Destructive list operations,  Prev: Lists as sets,  Up: Common List Functions
  718. Lists as sequences
  719. ------------------
  720.  -- Function: position OBJ LST
  721.      `position' returns the 0-based position of OBJ in LST, or `#f' if
  722.      OBJ does not occur in LST.
  723.      Example:
  724.           (position 'foo '(foo bar baz bang))
  725.              => 0
  726.           (position 'baz '(foo bar baz bang))
  727.              => 2
  728.           (position 'oops '(foo bar baz bang))
  729.              => #f
  730.  -- Function: reduce P LST
  731.      `reduce' combines all the elements of a sequence using a binary
  732.      operation (the combination is left-associative).  For example,
  733.      using `+', one can add up all the elements.  `reduce' allows you to
  734.      apply a function which accepts only two arguments to more than 2
  735.      objects.  Functional programmers usually refer to this as "foldl".
  736.      `collect:reduce' (*Note Collections::) provides a version of
  737.      `collect' generalized to collections.
  738.      Example:
  739.           (reduce + '(1 2 3 4))
  740.              => 10
  741.           (define (bad-sum . l) (reduce + l))
  742.           (bad-sum 1 2 3 4)
  743.              == (reduce + (1 2 3 4))
  744.              == (+ (+ (+ 1 2) 3) 4)
  745.           => 10
  746.           (bad-sum)
  747.              == (reduce + ())
  748.              => ()
  749.           (reduce string-append '("hello" "cruel" "world"))
  750.              == (string-append (string-append "hello" "cruel") "world")
  751.              => "hellocruelworld"
  752.           (reduce anything '())
  753.              => ()
  754.           (reduce anything '(x))
  755.              => x
  756.      What follows is a rather non-standard implementation of `reverse'
  757.      in terms of `reduce' and a combinator elsewhere called "C".
  758.           ;;; Contributed by Jussi Piitulainen (jpiitula@ling.helsinki.fi)
  759.           
  760.           (define commute
  761.             (lambda (f)
  762.               (lambda (x y)
  763.                 (f y x))))
  764.           
  765.           (define reverse
  766.             (lambda (args)
  767.               (reduce-init (commute cons) args)))
  768.  -- Function: reduce-init P INIT LST
  769.      `reduce-init' is the same as reduce, except that it implicitly
  770.      inserts INIT at the start of the list.  `reduce-init' is preferred
  771.      if you want to handle the null list, the one-element, and lists
  772.      with two or more elements consistently.  It is common to use the
  773.      operator's idempotent as the initializer.  Functional programmers
  774.      usually call this "foldl".
  775.      Example:
  776.           (define (sum . l) (reduce-init + 0 l))
  777.           (sum 1 2 3 4)
  778.              == (reduce-init + 0 (1 2 3 4))
  779.              == (+ (+ (+ (+ 0 1) 2) 3) 4)
  780.              => 10
  781.           (sum)
  782.              == (reduce-init + 0 '())
  783.           => 0
  784.           
  785.           (reduce-init string-append "@" '("hello" "cruel" "world"))
  786.              == (string-append (string-append (string-append "@" "hello") "cruel") "world")
  787.              => "@hellocruelworld"
  788.      Given a differentiation of 2 arguments, `diff', the following will
  789.      differentiate by any number of variables.
  790.           (define (diff* exp . vars)
  791.             (reduce-init diff exp vars))
  792.      Example:
  793.           ;;; Real-world example:  Insertion sort using reduce-init.
  794.           
  795.           (define (insert l item)
  796.             (if (null? l)
  797.                 (list item)
  798.                 (if (< (car l) item)
  799.                     (cons (car l) (insert (cdr l) item))
  800.                     (cons item l))))
  801.           (define (insertion-sort l) (reduce-init insert '() l))
  802.           
  803.           (insertion-sort '(3 1 4 1 5)
  804.              == (reduce-init insert () (3 1 4 1 5))
  805.              == (insert (insert (insert (insert (insert () 3) 1) 4) 1) 5)
  806.              == (insert (insert (insert (insert (3)) 1) 4) 1) 5)
  807.              == (insert (insert (insert (1 3) 4) 1) 5)
  808.              == (insert (insert (1 3 4) 1) 5)
  809.              == (insert (1 1 3 4) 5)
  810.              => (1 1 3 4 5)
  811.  -- Function: butlast LST N
  812.      `butlast' returns all but the last N elements of LST.
  813.      Example:
  814.           (butlast '(1 2 3 4) 3)
  815.              => (1)
  816.           (butlast '(1 2 3 4) 4)
  817.              => ()
  818.  -- Function: nthcdr N LST
  819.      `nthcdr' takes N `cdr's of LST and returns the result.  Thus
  820.      `(nthcdr 3 LST)' == `(cdddr LST)'
  821.      Example:
  822.           (nthcdr 2 '(1 2 3 4))
  823.              => (3 4)
  824.           (nthcdr 0 '(1 2 3 4))
  825.              => (1 2 3 4)
  826.  -- Function: last LST N
  827.      `last' returns the last N elements of LST.  N must be a
  828.      non-negative integer.
  829.      Example:
  830.           (last '(foo bar baz bang) 2)
  831.              => (baz bang)
  832.           (last '(1 2 3) 0)
  833.              => 0
  834. File: slib.info,  Node: Destructive list operations,  Next: Non-list Common LISP functions,  Prev: Lists as sequences,  Up: Common List Functions
  835. Destructive list operations
  836. ---------------------------
  837.   These procedures may mutate the list they operate on, but any such
  838. mutation is undefined.
  839.  -- Procedure: nconc ARGS
  840.      `nconc' destructively concatenates its arguments.  (Compare this
  841.      with `append', which copies arguments rather than destroying them.)
  842.      Sometimes called `append!' (*Note Rev2 Procedures::).
  843.      Example:  You want to find the subsets of a set.  Here's the
  844.      obvious way:
  845.           (define (subsets set)
  846.             (if (null? set)
  847.                 '(())
  848.                 (append (mapcar (lambda (sub) (cons (car set) sub))
  849.                                 (subsets (cdr set)))
  850.                         (subsets (cdr set)))))
  851.      But that does way more consing than you need.  Instead, you could
  852.      replace the `append' with `nconc', since you don't have any need
  853.      for all the intermediate results.
  854.      Example:
  855.           (define x '(a b c))
  856.           (define y '(d e f))
  857.           (nconc x y)
  858.              => (a b c d e f)
  859.           x
  860.              => (a b c d e f)
  861.      `nconc' is the same as `append!' in `sc2.scm'.
  862.  -- Procedure: nreverse LST
  863.      `nreverse' reverses the order of elements in LST by mutating
  864.      `cdr's of the list.  Sometimes called `reverse!'.
  865.      Example:
  866.           (define foo '(a b c))
  867.           (nreverse foo)
  868.              => (c b a)
  869.           foo
  870.              => (a)
  871.      Some people have been confused about how to use `nreverse',
  872.      thinking that it doesn't return a value.  It needs to be pointed
  873.      out that
  874.           (set! lst (nreverse lst))
  875.      is the proper usage, not
  876.           (nreverse lst)
  877.      The example should suffice to show why this is the case.
  878.  -- Procedure: delete! ELT LST
  879.  -- Procedure: delete-if! PRED LST
  880.      Destructive versions of `remove' and `remove-if', called `delete'
  881.      and `delete-if' in Common LISP.
  882.      Example:
  883.           (define lst '(foo bar baz bang))
  884.           (delete! 'foo lst)
  885.              => (bar baz bang)
  886.           lst
  887.              => (foo bar baz bang)
  888.           
  889.           (define lst '(1 2 3 4 5 6 7 8 9))
  890.           (delete-if! odd? lst)
  891.              => (2 4 6 8)
  892.           lst
  893.              => (1 2 4 6 8)
  894.      Some people have been confused about how to use `delete!' or
  895.      `delete-if!', thinking that they dont' return a value.  It needs to
  896.      be pointed out that
  897.           (set! lst (delete! el lst))
  898.      is the proper usage, not
  899.           (delete! el lst)
  900.      The examples should suffice to show why this is the case.
  901. File: slib.info,  Node: Non-list Common LISP functions,  Next: Tree operations,  Prev: Destructive list operations,  Up: Common List Functions
  902. Non-list Common LISP functions
  903. ------------------------------
  904.  -- Function: and? . ARGS
  905.      `and?' checks to see if all its arguments are true.  If they are,
  906.      `and?' returns `#t', otherwise, `#f'.  (In contrast to `and', this
  907.      is a function, so all arguments are always evaluated and in an
  908.      unspecified order.)
  909.      Example:
  910.           (and? 1 2 3)
  911.              => #t
  912.           (and #f 1 2)
  913.              => #f
  914.  -- Function: or? . ARGS
  915.      `or?' checks to see if any of its arguments are true.  If any is
  916.      true, `or?' returns `#t', and `#f' otherwise.  (To `or' as `and?'
  917.      is to `and'.)
  918.      Example:
  919.           (or? 1 2 #f)
  920.              => #t
  921.           (or? #f #f #f)
  922.              => #f
  923.  -- Function: atom? OBJECT
  924.      Returns `#t' if OBJECT is not a pair and `#f' if it is pair. 
  925.      (Called `atom' in Common LISP.)
  926.           (atom? 1)
  927.              => #t
  928.           (atom? '(1 2))
  929.              => #f
  930.           (atom? #(1 2))   ; dubious!
  931.              => #t
  932. File: slib.info,  Node: Tree operations,  Prev: Non-list Common LISP functions,  Up: Common List Functions
  933. Tree operations
  934. ---------------
  935.   These are operations that treat lists a representations of trees.
  936.  -- Function: subst NEW OLD TREE
  937.  -- Function: substq NEW OLD TREE
  938.  -- Function: substv NEW OLD TREE
  939.      `subst' makes a copy of TREE, substituting NEW for every subtree
  940.      or leaf of TREE which is `equal?' to OLD and returns a modified
  941.      tree.  The original TREE is unchanged, but may share parts with
  942.      the result.
  943.      `substq' and `substv' are similar, but test against OLD using
  944.      `eq?' and `eqv?' respectively.
  945.      Examples:
  946.           (substq 'tempest 'hurricane '(shakespeare wrote (the hurricane)))
  947.              => (shakespeare wrote (the tempest))
  948.           (substq 'foo '() '(shakespeare wrote (twelfth night)))
  949.              => (shakespeare wrote (twelfth night . foo) . foo)
  950.           (subst '(a . cons) '(old . pair)
  951.                  '((old . spice) ((old . shoes) old . pair) (old . pair)))
  952.              => ((old . spice) ((old . shoes) a . cons) (a . cons))
  953.  -- Function: copy-tree TREE
  954.      Makes a copy of the nested list structure TREE using new pairs and
  955.      returns it.  All levels are copied, so that none of the pairs in
  956.      the tree are `eq?' to the original ones -- only the leaves are.
  957.      Example:
  958.           (define bar '(bar))
  959.           (copy-list (list bar 'foo))
  960.              => ((bar) foo)
  961.           (eq? bar (car (copy-list (list bar 'foo))))
  962.              => #f
  963.